<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Dao;

use App\Model\DiaryContent;
use App\Model\UserDiary;

class UserDiaryDao
{
    /**
     * 增加一条记录.
     * @param $data
     */
    public function addDiary($data): void
    {
        /**
         * @var UserDiary $userDiary
         */
        $userDiary = new UserDiary();
        $userDiary->user_id = $data['user_id'];
        $userDiary->date = get_date();
        $userDiary->is_private = $data['is_private'];
        $userDiary->address = get_address_code($data['address']);
        $userDiary->save();
        /**
         * @var DiaryContent $diaryContent
         */
        $diaryContent = new DiaryContent();
        $diaryContent->d_id = $userDiary->id;
        $diaryContent->content = $data['content'];
        //$diaryContent->userDiary()->associate($userDiary);
        $diaryContent->save();
    }

    /**
     * @param $userId
     * @param $id
     */
    public function getDiaryInfo($userId, $id): array
    {
        $info = UserDiary::where('id', $id)
            ->where('user_id', $userId)
            ->get();
        if (empty($info)) {
            return [];
        }
        return $info->toArray();
    }

    /**
     * 删除日记.
     * @param $id
     */
    public function deleteDiary($id): void
    {
        $diary = UserDiary::find($id);
        $diary->delete();
        $diary->diaryContent()->delete();
    }
}
